<template>
  <!-- 新增部门的弹层 -->
  <!-- :model  :rules  prop   v-model -->
  <!-- 对话框才有close open 事件 -->
  <el-dialog :title="showTitle" :visible="showDialog" @open="handleOpen" @close="handleCloseDialog">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <!-- label显示出来给用户看的  value将来收集提交给后台的 -->
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetSimpleUserList } from '@/api/user'
import { reqAddDepartment, reqGetDepartDetail, reqUpdateDepartments } from '@/api/departments'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      required: true
    },
    deptList: {
      type: Array,
      required: true
    }
  },

  data() {
    const validateName = (rules, value, callback) => {
      // 1. 根据老父亲 nodeData.id 作为 item.pid, 找所有兄弟
      // console.log(value, this.nodeData.id, this.deptList)
      let arr = []
      if (this.form.id) {
        // 编辑操作
        if (this.nodeData.name === value) {
          callback()
          return
        }
        arr = this.deptList.filter(item => item.pid === this.nodeData.id)
      } else {
        arr = this.deptList.filter(item => item.pid === this.nodeData.id)
      }

      // 2. 只要 value 和 arr 中任意一个部门的 name 相等，就不通过校验
      const isRepeat = arr.some(item => item.name === value)

      // 3. 判断，是否重复
      isRepeat ? callback(new Error('已经出现了同名的部门了')) : callback()

      // if (isRepeat) {
      //   callback(new Error('已经出现了同名的部门了'))
      // } else {
      //   callback()
      // }
    }

    const validateCode = (rules, value, callback) => {
      if (this.form.id && value === this.nodeData.code) {
        // 编辑情况下:code 可以和原来的一样，通过校验
        callback()
        return
      }
      // 检查 value 是否在所有的部门列表 （this.deptList）中是否有重复
      const isRepeat = this.deptList.some(item => item.code === value)
      isRepeat ? callback(new Error('部门编码已存在')) : callback()
    }

    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      userList: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '部门名称必须是1-10位字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '部门编码必须是1-10位字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍必须是1-300位字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    // this.getSimpleUserList()

  },
  methods: {
    handleCloseDialog() {
      // console.log(11)
      this.$emit('update:showDialog', false)
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }

      this.$refs.form.resetFields()
    },
    // this.$refs.xx.getSimpleUserList()
    async getSimpleUserList() {
      // console.log('发送请求，获取员工简单列表')
      const { data } = await reqGetSimpleUserList()
      this.userList = data
    }, // 发送请求，获取编辑需要的详情，进行回显
    async getDepartDetail() {
      const { data } = await reqGetDepartDetail(this.nodeData.id)
      // 回显的过程除了进行基本数据的赋值之外，还会多一个数据，就是 id
      this.form = data
    },

    handleOpen() {
      // console.log('这里发请求也行')
      this.getSimpleUserList()
    },

    clickSubmit() {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await reqUpdateDepartments(this.from)
          this.$message.success('添加成功')
        } else {
          // 通过了校验
          await reqAddDepartment({
            ...this.form,
            pid: this.nodeData.id
          })
          this.$message.success('新增部门成功')
          // 关闭弹框
          this.handleCloseDialog()
          // 重新渲染
          this.$emit('add-depts')
        }
      })
    }
  }
}
</script>

<style>

</style>
